(function () {
    var myChart = echarts.init(document.querySelector('.map .chart'));
    var mapName = 'china'

    // 获取后端数据的函数
    async function fetchData() {
        const response = await fetch('/test?province=&year=2018');
        const data = await response.json();
        return data;
    }

    // 从后端获取数据
    fetchData().then(priceDataList => {
        // 根据后端返回的数据生成ECharts所需的数据格式
        var data = priceDataList.map(item => ({
            name: item.province,
            value: item.averagePrice,
        }));

        var option = {
            tooltip: {
                trigger: 'item'
            },
            visualMap: {
                min: 0,
                max: 200,  // 这里你可能需要根据实际情况调整
                left: 'left',
                top: 'bottom',
                text: ['高', '低'],
                calculable: true,
                seriesIndex: [1],
                inRange: {
                    color: ['#e6f7ff', '#1890FF','#0050b3']
                }
            },
            geo: {
                show: true,
                map: mapName,
                label: {
                    normal: {
                        show: false
                    },
                    emphasis: {
                        show: false,
                    }
                },
                roam: false,
                itemStyle: {
                    normal: {
                        areaColor: 'rgba(20,41,87,0.8)',
                        borderColor: '#195bb9',
                    },
                    emphasis: {
                        areaColor: '#2B91B7',
                    }
                }
            },
            series: [
                {
                    type: 'map',
                    map: mapName,
                    geoIndex: 0,
                    aspectScale: 0.75,
                    showLegendSymbol: false,
                    label: {
                        normal: {
                            show: true
                        },
                        emphasis: {
                            show: false,
                            textStyle: {
                                color: '#fff'
                            }
                        }
                    },
                    roam: true,
                    itemStyle: {
                        normal: {
                            areaColor: '#031525',
                            borderColor: '#3B5077',
                        },
                        emphasis: {
                            areaColor: '#2B91B7'
                        }
                    },
                    animation: false,
                    data: data
                },
            ]
        };
        myChart.setOption(option);
        window.addEventListener('resize',function(){
            myChart.resize();
        });
    });
})();
